package com.magiccompass.alipay.barcode.controller;

import java.net.URI;
import java.util.TreeMap;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import com.magiccompass.alipay.barcode.constants.AlipayPartnerConstants;
import com.magiccompass.alipay.barcode.entity.AlipayBarcodePaymentRequest;
import com.magiccompass.alipay.barcode.entity.AlipayBarcodeReverseRequest;
import com.magiccompass.alipay.barcode.entity.MerchantTransaction;
import com.magiccompass.alipay.barcode.model.AlipayBarcodeAllResponseAJAXModel;
import com.magiccompass.alipay.barcode.responsehandler.ReverseResponseHandler;
import com.magiccompass.alipay.barcode.security.model.LoginUserModel;
import com.magiccompass.alipay.barcode.service.AlipayBarcodeService;
import com.magiccompass.alipay.barcode.service.MerchantBusinessService;
import com.magiccompass.alipay.barcode.util.AlipayBarcodeRequestUtil;
import com.magiccompass.alipay.barcode.util.UrlUtil;
import com.magiccompass.alipay.barcode.util.UserUtil;

@Controller
@RequestMapping(value="/alipayBarcodeReverseController")
public class AlipayBarcodeReverseController {
	@Resource(name="alipayBarcodeService")
	private AlipayBarcodeService alipayBarcodeService;
	@Resource(name="merchantBusinessService")
	private MerchantBusinessService merchantBusinessService;
	
	@RequestMapping(value="/reverseTest", method = {RequestMethod.GET,RequestMethod.POST})
    public String barcodeReverseTest(Model model,HttpServletRequest request) {
		return "alipay_barcode_gateway/reverseTest";
    }
	
	@RequestMapping(value="/reverse", method = {RequestMethod.GET,RequestMethod.POST}, produces = "application/json; charset=UTF-8")
    public @ResponseBody AlipayBarcodeAllResponseAJAXModel alipayBarcodeReverse(Model model,HttpServletRequest request) {
		String mtIdStr = request.getParameter("mtId");
		AlipayBarcodeAllResponseAJAXModel returnJSON = handleReverse(request,mtIdStr,alipayBarcodeService,merchantBusinessService);
		return returnJSON;
    }
	
	public AlipayBarcodeAllResponseAJAXModel paymentDirectReverse(HttpServletRequest request,String mtIdStr,AlipayBarcodeService abService,MerchantBusinessService mbService) {
		AlipayBarcodeAllResponseAJAXModel returnJSON = handleReverse(request,mtIdStr,abService,mbService);
		return returnJSON;
    }
	
	public AlipayBarcodeAllResponseAJAXModel handleReverse(HttpServletRequest request,String mtIdStr,AlipayBarcodeService abService,MerchantBusinessService mbService) {
			Integer mtId = new Integer(mtIdStr);
			
			MerchantTransaction mt =  mbService.findMerchantTransactionById(mtId);

			AlipayBarcodePaymentRequest abpr = abService.findAlipayBarcodePaymentRequestByMerchantTransactionId(mtId);
			
			AlipayBarcodeAllResponseAJAXModel returnJSON = new AlipayBarcodeAllResponseAJAXModel();
			returnJSON.setSuccess("true");
			returnJSON.setRedirect("true");
			returnJSON.setRedirectURL(request.getContextPath()+"/alipayBarcodeReverseController/result");
			
			LoginUserModel currentUser = UserUtil.getCurrentLoginUser();
			if(mt.getMerchant().getId().equals(currentUser.getDbUserInfo().getMerchant().getId())){ // merchant permit reverse it's own transaction
				if(abpr != null){ //Merchant Transaction request is in unknown status
					if(AlipayBarcodeRequestUtil.isPaymentCanBeReversed(abpr)){
						AlipayBarcodeReverseRequest abrreq = AlipayBarcodeRequestUtil.alipayBarcodeReverseRequestEntityInit(mt,currentUser.getLoginUserId());
	
						TreeMap<String,String> barcodeRequestParameter4AlipayTreeMap = AlipayBarcodeRequestUtil.makeParameterMap4Alipay(abrreq,abService);
						String sign = AlipayBarcodeRequestUtil.getSign(barcodeRequestParameter4AlipayTreeMap);
						abrreq.setSign(sign);
						abService.save(abrreq);
						
						barcodeRequestParameter4AlipayTreeMap.put("sign", abrreq.getSign());
						barcodeRequestParameter4AlipayTreeMap.put("sign_type", AlipayPartnerConstants.SIGN_TYPE);				
						
						if(abrreq.getId() != null){ // success insert into DB
							try {						
								RestTemplate restTemplate = new RestTemplate();
								String alipayBarcodeServerURL = AlipayPartnerConstants.ALIPAY_GATEWAY;
						    	String alipayBarcodeParameter = UrlUtil.makeParameterMap2String(barcodeRequestParameter4AlipayTreeMap);
						    	String restURL = alipayBarcodeServerURL+"?"+alipayBarcodeParameter;
						    	System.out.println("restURL:"+restURL);
						    	URI uri = new URI(restURL);
								//String response = restTemplate.getForObject(restURL, String.class);
						    	String response = restTemplate.getForObject(uri, String.class);
						    	//String response = ReverseResponseHandler.RESULT_REVERSE_FAILED_4_TEST;
								System.out.println("response is:"+response);
								
								AlipayBarcodeAllResponseAJAXModel alipayResponse = ReverseResponseHandler.handleResponse(response, abrreq,abpr, abService);
								returnJSON.setResponseResultCode(alipayResponse.getResponseResultCode());
								returnJSON.setResponseResultReason(alipayResponse.getResponseResultReason());
							} catch (Exception e) {
								e.printStackTrace();
								returnJSON.setResponseResultCode("UNEXPECTED EXCEPTION");
								returnJSON.setResponseResultReason("Unexpected exception happened. Please contact support.");
							}
				    	}else{
				    		returnJSON.setResponseResultCode("UNEXPECTED");
							returnJSON.setResponseResultReason("Unexpected ERROR happened. Please contact support.");
				    	}
					}else{
						returnJSON.setResponseResultCode("ERROR");
						returnJSON.setResponseResultReason("This transaction can't reverse. Please contact support.");
					}				
				}else{
					returnJSON.setResponseResultCode("ERROR");
					returnJSON.setResponseResultReason("This transaction can't reverse.");				
				}
			}
			return returnJSON;
	    }
	
	@RequestMapping(value="/result", method = {RequestMethod.GET,RequestMethod.POST})
    public String result(Model model,HttpServletRequest request) {
		String resultCode = request.getParameter("resultCode");
		String resultReason = request.getParameter("resultReason");
		
		String messageType = "alert-danger";
		if("SUCCESS".equals(resultCode)){
			messageType = "alert-success";
		}
		
		String message = "Your operation result is "+resultCode+". "+resultReason;
		
		model.addAttribute("message",message);
		model.addAttribute("messageType",messageType);
		return "common/result";
    }
}
